<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use Spatie\Permission\Models\Permission;
use App\Http\Requests\Api\PermissionRequest;
use Spatie\Permission\Models\Permission;
use App\Transformers\PermissionTransformer;

class PermissionsController extends Controller
{

    public function index(Request $request, Permission $permission)
    {
        $this->authorize('update', $permission);

        $per_page = $request->input('per_page', 20);
        $query = $permission->query();

        $permissions = $query->->recent()->paginate($per_page);

        return $this->response->paginator($permissions, new PermissionTransformer());
    }

    public function userIndex(Request $request, Permission $permission)
    {
        $per_page = $request->input('per_page', 20);
        // $query = $permission->query();

        // $permissions = $query->recent()->paginate($per_page);
        $permissions = $this->user->permissions()->recent()->paginate($per_page);

        return $this->response->paginator($permissions, new PermissionTransformer());
    }

    public function show(Permission $permission)
    {
        $this->authorize('update', $permission);

        return $this->response->item($permission, new PermissionTransformer());
    }

    public function store(PermissionRequest $request, Permission $permission)
    {

        $this->authorize('update', $permission);

        $permission->fill($request->all());
        $permission->save();

        return $this->response->item($permission, new PermissionTransformer())
            ->setStatusCode(201);
    }

    public function update(PermissionRequest $request, Permission $permission)
    {
        $this->authorize('update', $permission);

        $permission->update($request->all());

        return $this->response->item($permission, new PermissionTransformer());
    }

    public function destroy(Permission $permission)
    {
        $this->authorize('destroy', $permission);

        $permission->delete();

        return $this->response->array([
            'status'=>true,
            'data'=>[
                'successflag'=>true,
            ],
            'message'=>'删除成功',
        ])->setStatusCode(200);
    }
}
